<template>
    <!-- 对话框表单 -->
    <el-dialog class="ba-operate-dialog" :close-on-click-modal="false" :destroy-on-close="true"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)" @close="handleClose" width="1200px">
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ dialogTitle }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div class="ba-operate-form" :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'">
                <el-form ref="formRef" :model="safeFormItems" :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'" :rules="rules" v-if="!baTable.form.loading">
                    <!-- 基本信息 -->
                    <div class="form-section">
                        <el-form-item label="商品分类" prop="category_id">
                            <el-select v-model="baTable.form.items!.category_id" placeholder="请选择分类" clearable
                                class="w100">
                                <el-option v-for="category in categoryOptions" :key="category.id"
                                    :label="category.label" :value="category.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="所属商家" prop="business_id">
                            <el-select v-model="baTable.form.items!.business_id" placeholder="请选择商家" clearable
                                class="w100">
                                <el-option v-for="merchant in merchantOptions" :key="merchant.id"
                                    :label="merchant.label" :value="merchant.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="title" label="商品标题">
                            <el-input v-model="baTable.form.items!.title" type="string"
                                placeholder="请输入商品标题"></el-input>
                        </el-form-item>
                        <el-form-item prop="flag" label="标签">
                            <el-input-tag draggable tag-effect="dark" tag-type="primary"
                                v-model="baTable.form.items!.flag" placeholder="请输入标签"></el-input-tag>
                        </el-form-item>
                        <el-form-item prop="sku" label="商品编号">
                            <el-input v-model="baTable.form.items!.sku" type="string" placeholder="请输入商品编号"></el-input>
                        </el-form-item>
                        <FormItem label="缩略图" type="image" v-model="baTable.form.items!.image" :inputAttr="{ listType: 'picture-card', style: { '--el-upload-picture-card-size': '120px' } }" />
                        <FormItem label="组图" type="images" v-model="baTable.form.items!.images" />
                        <FormItem label="视频" type="file" v-model="baTable.form.items!.files"
                            :input-attr="{ accept: 'video/*' }" />
                        <el-form-item prop="intro" label="简介">
                            <el-input v-model="baTable.form.items!.intro" type="string" placeholder="请输入简介"></el-input>
                        </el-form-item>
                        <FormItem label="服务类型" type="remoteSelects" v-model="baTable.form.items!.goods_notice_ids"
                            :input-attr="{ remoteUrl: '/goods/notice/index', pk: 'id', field: 'content' }" />
                        <!-- 规格类型 -->
                        <FormItem label="规格类型" v-model="baTable.form.items!.spec_type" type="radio" :input-attr="{
                            border: true,
                            content: { 1: '单规格', 2: '多规格' },
                        }" />
                        <!-- 单规格区域 -->
                        <template v-if="baTable.form.items?.spec_type === 1">
                            <el-form-item prop="price" label="价格">
                                <el-input type="number" v-model="baTable.form.items!.price" :min="0" :step="0.01"
                                    :precision="2" placeholder="请输入商品价格" style="width: 100%"></el-input>
                            </el-form-item>
                            <el-form-item prop="svip_price" label="SVIP价格">
                                <el-input type="number" v-model="baTable.form.items!.svip_price" :min="0" :step="0.01"
                                    :precision="2" placeholder="请输入VIP价格" style="width: 100%"></el-input>
                            </el-form-item>
                            <el-form-item prop="inventory" label="商品库存">
                                <el-input type="number" v-model="baTable.form.items!.inventory" :min="0" :step="1"
                                    placeholder="请输入商品库存" style="width: 100%"></el-input>
                            </el-form-item>
                        </template>

                        <!-- 多规格属性（仅在选择多规格时显示） -->
                        <template v-else>
                            <el-form-item prop="price" label="规格名称">
                                <div class="form-sku">
                                    <div class="spec-name-input">
                                        <el-input v-model="sku1" placeholder="输入规格名称（如颜色）"
                                            style="width: 200px; margin-right: 10px;" />
                                        <el-button type="primary" @click="addSpecName" :disabled="!sku1.trim()">
                                            <el-icon>
                                                <Plus />
                                            </el-icon>
                                            添加规格
                                        </el-button>
                                    </div>

                                    <!-- 规格属性值管理 -->
                                    <div v-for="(spec, specIndex) in sku_price" :key="specIndex"
                                        class="spec-attribute-item">
                                        <div class="spec-header">
                                            <h4>{{ spec.name }}</h4>
                                            <el-button type="danger" size="small" @click="removeSpecName(specIndex)"
                                                :disabled="sku_price.length <= 1">
                                                <el-icon>
                                                    <Delete />
                                                </el-icon>
                                            </el-button>
                                        </div>
                                        <div class="spec-values">
                                            <div v-for="(value, valueIndex) in spec.values" :key="valueIndex"
                                                class="spec-value-tag">
                                                <span>{{ value }}</span>
                                                <el-button type="danger" size="small" circle
                                                    @click="removeSpecValue(specIndex, valueIndex)">
                                                    <el-icon>
                                                        <Delete />
                                                    </el-icon>
                                                </el-button>
                                            </div>
                                            <el-input v-model="spec.newValue" placeholder="输入规格值"
                                                style="width: 150px; margin-right: 10px;"
                                                @keyup.enter="addSpecValue(specIndex)" />
                                            <el-button type="primary" size="small" @click="addSpecValue(specIndex)"
                                                :disabled="!spec.newValue.trim()">
                                                <el-icon>
                                                    <Plus />
                                                </el-icon>
                                                追加
                                            </el-button>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-sku">
                                    <el-table v-if="skuList.length > 0" :data="skuList" border style="width: 100%">
                                        <el-table-column prop="index" label="序号" width="60" />
                                        <el-table-column label="规格封面" width="120">
                                            <template #default="scope">
                                                <el-upload class="avatar-uploader" action="" :auto-upload="false"
                                                    :on-change="(file) => handleSpecImageUpload(file, scope.row)"
                                                    :show-file-list="false"
                                                    accept="image/gif, image/jpg, image/jpeg, image/bmp, image/png, image/webp">
                                                    <img v-if="scope.row.image" :src="scope.row.image" class="avatar" />
                                                    <el-button v-else type="primary" size="small">上传图片</el-button>
                                                </el-upload>
                                            </template>
                                        </el-table-column>
                                        <template v-for="(spec, index) in sku_price" :key="index">
                                            <el-table-column :prop="`specs.${index}`" :label="spec.name" width="100" />
                                        </template>
                                        <el-table-column prop="price" label="价格">
                                            <template #default="scope">
                                                <el-input type="number" v-model="scope.row.price" :min="0" :step="0.01"
                                                    :precision="2" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="svip_price" label="SVIP价格">
                                            <template #default="scope">
                                                <el-input type="number" v-model="scope.row.svip_price" :min="0"
                                                    :step="0.01" :precision="2" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="inventory" label="库存">
                                            <template #default="scope">
                                                <el-input type="number" v-model="scope.row.inventory" :min="0"
                                                    :step="1" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="操作" width="80">
                                            <template #default="scope">
                                                <el-switch v-model="scope.row.is_del" :active-value="0"
                                                    :inactive-value="1" active-color="#f56c6c" inactive-color="#67c23a"
                                                    @change="toggleSkuStatus(scope.row)" />
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <div v-else class="no-sku-hint">请先添加规格属性和值</div>
                                </div>
                            </el-form-item>

                        </template>


                        <el-form-item prop="line_price" label="划线价">
                            <el-input v-model="baTable.form.items!.line_price" type="string"
                                placeholder="请输入划线价"></el-input>
                        </el-form-item>
                        <el-form-item prop="unit" label="单位">
                            <el-input v-model="baTable.form.items!.unit" type="string" placeholder="请输入单位"></el-input>
                        </el-form-item>
                        <el-form-item prop="sales" label="销量">
                            <el-input v-model="baTable.form.items!.sales" type="string" placeholder="请输入销量"></el-input>
                        </el-form-item>
                        <el-form-item prop="gift_score" label="赠送积分">
                            <el-input v-model="baTable.form.items!.gift_score" type="string"
                                placeholder="赠送多少积分,0表示不送"></el-input>
                        </el-form-item>
                        <el-form-item prop="person_num" label="每人限购">
                            <el-input v-model="baTable.form.items!.person_num" type="string"
                                placeholder="每人限购多少件,0表示不限制"></el-input>
                        </el-form-item>
                        <el-form-item prop="order_num" label="每单限购">
                            <el-input v-model="baTable.form.items!.order_num" type="string"
                                placeholder="每单限购多少件,0表示不限制"></el-input>
                        </el-form-item>

                        <el-form-item label="产品参数">
                            <div class="params-container">
                                <div class="params-header">
                                    <div class="param-col-name">名称</div>
                                    <div class="param-col-value">参数</div>
                                    <div class="param-col-action">操作</div>
                                </div>
                                <div v-for="(param, index) in productParams" :key="index" class="param-item">
                                    <el-input v-model="param.label" placeholder="名称" class="param-input-name" />
                                    <el-input v-model="param.value" placeholder="参数" class="param-input-value" />
                                    <div class="param-actions">
                                        <el-button type="danger" size="small" @click="removeParam(index)">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>
                                        </el-button>
                                    </div>
                                </div>
                                <el-button type="primary" size="small" @click="addParam" class="add-param-btn">
                                    <el-icon>
                                        <Plus />
                                    </el-icon> 追加
                                </el-button>
                            </div>
                        </el-form-item>

                        <!-- 详情 富文本 -->
                        <FormItem label="详情" type="editor" v-model="baTable.form.items!.content"></FormItem>
                        <el-form-item prop="views" label="浏览量">
                            <el-input v-model="baTable.form.items!.views" type="number" :min="0" :step="1"
                                placeholder="请输入浏览量"></el-input>
                        </el-form-item>
                        <el-form-item prop="weight" label="排序">
                            <el-input v-model="baTable.form.items!.weight" type="number" :min="0" :step="1"
                                placeholder="请输入排序号"></el-input>
                        </el-form-item>

                        <FormItem label="是否推荐" v-model="baTable.form.items!.istuijian" type="radio" :input-attr="{
                            border: true,
                            content: { 0: '否', 1: '是' },
                        }" />
                        <FormItem label="商品状态" v-model="baTable.form.items!.status" type="radio" :input-attr="{
                            border: true,
                            content: { 0: '下架', 1: '上架' },
                        }" />
                    </div>
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">取消</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="handleSave" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? '保存并编辑下一项' :
                        '保存' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import createAxios from '/@/utils/axios'
import { reactive, inject, useTemplateRef, computed, onMounted, ref, watch } from 'vue'
import type baTableClass from '/@/utils/baTable'
import type { FormItemRule } from 'element-plus'
import FormItem from '/@/components/formItem/index.vue'
import { buildValidatorData } from '/@/utils/validate'
import { useConfig } from '/@/stores/config'
import { ElMessage, ElLoading } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { fileUpload } from '/@/api/common'

// 在组件挂载时初始化表单数据
onMounted(() => {
    console.log('商家选择器组件已在页面中渲染')
    fetchCategories() // 加载分类数据
    fetchMerchants() // 加载商家数据
})


const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass

// 监听弹窗打开事件，在弹窗显示时初始化表单默认值
watch(() => baTable.form.operate, (newOperate) => {
    if (newOperate === 'Add' || newOperate === 'Edit') {
        console.log('弹窗打开，执行初始化:', newOperate)
        // 初始化表单默认值
        if (!baTable.form.items) {
            baTable.form.items = {}
        }
        if (!baTable.form.items.spec_type) {
            baTable.form.items.spec_type = 1 // 默认单规格
            console.log('baTable.form.items.spec_type', baTable.form.items.spec_type)
        }
    }
}, { immediate: true })
// 分类选项数据
const categoryOptions = ref<any[]>([])

// 商家选项数据
const merchantOptions = ref<any[]>([])

// SKU列表
const skuList = ref<any[]>([])

// 产品参数列表
const productParams = ref<any[]>([
    // 初始化一个空参数行
    { label: '', value: '' }
])

// 添加产品参数
function addParam() {
    productParams.value.push({ label: '', value: '' })
}

// 删除产品参数
function removeParam(index: number) {
    if (productParams.value.length > 1) {
        productParams.value.splice(index, 1)
    } else {
        // 如果只剩最后一行，清空内容而不是删除
        productParams.value[0].label = ''
        productParams.value[0].value = ''
    }
}

// 规格管理相关数据
const sku1 = ref('')
const sku_price = ref([
])

// 添加规格名称
function addSpecName() {
    if (!sku1.value.trim()) {
        ElMessage.warning('请输入规格名称')
        return
    }

    // 检查是否已存在同名规格
    if (sku_price.value.some(spec => spec.name === sku1.value.trim())) {
        ElMessage.warning('该规格名称已存在')
        return
    }

    sku_price.value.push({
        name: sku1.value.trim(),
        values: [],
        newValue: ''
    })

    sku1.value = ''
}

// 删除规格名称
function removeSpecName(index) {
    sku_price.value.splice(index, 1)
}

// 添加规格值
function addSpecValue(specIndex) {
    const spec = sku_price.value[specIndex]
    if (!spec || !spec.newValue || !spec.newValue.trim()) {
        ElMessage.warning('请输入规格值')
        return
    }

    if (spec.values && spec.values.includes(spec.newValue.trim())) {
        ElMessage.warning('该规格值已存在')
        return
    }

    spec.values.push(spec.newValue.trim())
    spec.newValue = ''

    // 添加规格值后立即生成SKU列表，同时保留已有数据
    generateSkuList()
}

// 删除规格值
function removeSpecValue(specIndex, valueIndex) {
    if (sku_price.value[specIndex] && sku_price.value[specIndex].values) {
        sku_price.value[specIndex].values.splice(valueIndex, 1)
    }
}

// 生成SKU组合
function generateSkuList() {
    if (!sku_price.value || sku_price.value.length === 0) {
        skuList.value = []
        return
    }

    // 过滤掉没有规格值的规格
    const validSpecs = sku_price.value.filter(spec => spec.values && spec.values.length > 0)

    // 如果没有有效的规格，则清空skuList
    if (validSpecs.length === 0) {
        skuList.value = []
        return
    }

    // 收集有效规格的规格值数组
    const valueArrays = validSpecs.map(spec => spec.values)

    // 生成笛卡尔积
    const combinations = generateCombinations(valueArrays)

    // 保存当前的SKU数据，用于后续匹配
    const oldSkuMap = new Map()
    skuList.value.forEach(sku => {
        const specKey = sku.specs.join(',') // 使用规格组合作为键
        oldSkuMap.set(specKey, {
            price: sku.price,
            svip_price: sku.svip_price,
            inventory: sku.inventory,
            image: sku.image,
            is_del: sku.is_del
        })
    })

    // 构建SKU列表 - 使用正确的字段名以匹配要求的格式，并保留已有数据
    skuList.value = combinations.map((specValues, index) => {
        const specKey = specValues.join(',')
        // 查找是否有匹配的旧数据
        const oldData = oldSkuMap.get(specKey) || {};

        return {
            index: index + 1,
            specs: [...specValues],
            price: oldData.price || '0.00', // 价格，字符串类型
            svip_price: oldData.svip_price || '0.00', // SVIP价格，字符串类型
            inventory: oldData.inventory || '0', // 库存，字符串类型
            image: oldData.image || '', // 保留已上传的图片
            is_del: oldData.is_del || 0,
            disabled: false
        }
    })
}

// 笛卡尔积生成函数
function generateCombinations(arrays) {
    if (!arrays || arrays.length === 0) return [[]]

    const [firstArray, ...remainingArrays] = arrays
    const remainingCombinations = generateCombinations(remainingArrays)

    return firstArray.flatMap(value =>
        remainingCombinations.map(combination => [value, ...combination])
    )
}

// 处理规格图片上传
function handleSpecImageUpload(file, row) {
    if (!file || !file.raw) return

    // 显示加载状态
    const loading = ElLoading.service({
        lock: true,
        text: '上传中...',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    // 创建FormData对象
    const fd = new FormData()
    fd.append('file', file.raw)

    // 调用通用上传函数
    fileUpload(fd, {}, false)
        .then((res) => {
            if (res.code === 1 && res.data) {
                // 上传成功，设置图片URL
                row.image = res.data.fullurl || res.data.url
                ElMessage.success('图片上传成功')
            } else {
                ElMessage.error(res.msg || '图片上传失败')
            }
        })
        .catch((error) => {
            console.error('图片上传失败:', error)
            ElMessage.error('图片上传失败，请重试')
        })
        .finally(() => {
            // 关闭加载状态
            loading.close()
        })
}

// 切换SKU状态
function toggleSkuStatus(row) {
    // 可以在这里添加额外的处理逻辑
    console.log('SKU状态切换:', row)
}

// 监听规格属性变化，自动生成SKU
watch(
    () => sku_price.value,
    () => {
        generateSkuList()
    },
    { deep: true, immediate: true }
)

// 获取分类数据的方法
const fetchCategories = async () => {
    try {
        console.log('开始获取分类数据...')
        const response = await createAxios({
            url: '/goods/category/index',
            method: 'get',
            params: {
                pageSize: 1000,
                field: 'id,name,pid,weight',
                orderBy: 'weight asc,id asc'
            }
        })

        console.log('分类数据响应:', response)

        // 检查响应数据格式
        if (!response || !response.data || !Array.isArray(response.data.rows)) {
            console.error('分类数据格式不正确:', response)
            return
        }

        const categories = response.data.rows
        const options: any[] = []

        // 构建ID到分类的映射
        const categoryMap: Record<number, any> = {}
        categories.forEach(cat => {
            categoryMap[cat.id] = cat
        })

        // 递归构建带有层级的选项
        const buildHierarchicalOptions = (parentId: number = 0, level: number = 0) => {
            const children = categories.filter(cat => cat.pid === parentId)
                .sort((a, b) => (a.weight || 0) - (b.weight || 0))
            children.forEach(child => {
                const indent = '　'.repeat(level)
                options.push({
                    id: child.id,
                    label: indent + (level > 0 ? '└─ ' : '') + child.name,
                    value: child.id
                })
                // 递归处理子分类
                buildHierarchicalOptions(child.id, level + 1)
            })
        }

        // 开始构建层级结构
        buildHierarchicalOptions()

        console.log('构建的分类选项:', options)
        categoryOptions.value = options
    } catch (error) {
        console.error('获取分类数据失败:', error)
    }
}

// 表单验证规则
const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    title: [buildValidatorData({ name: 'required', title: '商品标题' })],
    category_id: [buildValidatorData({ name: 'required', title: '商品分类' })],
    business_id: [buildValidatorData({ name: 'required', title: '所属商家' })],
})

// 安全访问form.items，避免undefined错误
const safeFormItems = computed(() => {
    if (!baTable.form.items) {
        baTable.form.items = {}
    }
    return baTable.form.items
})

// 对话框标题
const dialogTitle = computed(() => {
    if (baTable.form.operate === 'Add') {
        return '添加商品'
    } else if (baTable.form.operate === 'Edit') {
        return '编辑商品'
    }
    return ''
})


// 关闭对话框处理函数
const handleClose = () => {
    // 重置表单验证
    if (formRef.value) {
        formRef.value.resetFields()
    }
    // 调用baTable的toggleForm方法关闭表单
    baTable.toggleForm('')
}

// 保存按钮点击处理函数
const handleSave = () => {
    // 确保表单数据对象存在
    if (!baTable.form.items) {
        baTable.form.items = {}
    }

    // 格式化规格数据 - sku1格式
    const formattedSku1 = sku_price.value.map(spec => ({
        name: spec.name,
        value: [...spec.values]
    })).filter(item => item.value.length > 0) // 只包含有值的规格

    // 格式化SKU价格数据 - sku_price格式
    const formattedSkuPrice = skuList.value.map(sku => ({
        skus: [...sku.specs],
        price: sku.price?.toString() || '0.00',
        image: sku.image || '',
        is_del: sku.is_del || 0,
        svip_price: sku.svip_price?.toString() || '0.00',
        inventory: sku.inventory?.toString() || '0'
    }))

    // 格式化产品参数数据 - param格式
    const formattedParams = productParams.value
        .filter(param => param.label.trim() || param.value.trim()) // 过滤掉名称和值都为空的参数
        .map(param => ({
            label: param.label.trim(),
            value: param.value.trim()
        }))

    // 确保数值类型字段被正确转换
    const ensureNumberField = (fieldName: string) => {
        if (baTable.form.items[fieldName] !== undefined) {
            const value = baTable.form.items[fieldName]
            if (typeof value === 'string' && value.trim() === '') {
                baTable.form.items[fieldName] = 0
            } else {
                // 尝试转换为数字，但保留原值如果转换失败
                const num = Number(value)
                if (!isNaN(num)) {
                    baTable.form.items[fieldName] = num
                }
            }
        }
    }

    // 处理需要转换为数字的字段
    const numberFields = ['line_price', 'sales', 'gift_score', 'person_num', 'order_num', 'views', 'price', 'inventory', 'svip_price']
    numberFields.forEach(field => ensureNumberField(field))

    // 将格式化后的数据添加到表单中
    baTable.form.items.sku1 = formattedSku1
    baTable.form.items.sku_price = formattedSkuPrice
    baTable.form.items.param = formattedParams // 产品参数数组以param为键名保存

    // 打印表单数据
    console.log('表单数据:', baTable.form.items)
    console.log('sku1格式:', formattedSku1)
    console.log('sku_price格式:', formattedSkuPrice)
    console.log('产品参数格式:', formattedParams)

    // 直接在handleSave中处理表单验证和提交，避免设置baTable.form.ref
    const operate = baTable.form.operate!.replace(baTable.form.operate![0], baTable.form.operate![0].toLowerCase())

    if (baTable.runBefore('onSubmit', { formEl: formRef.value, operate: operate, items: baTable.form.items! }) === false) return

    // 表单验证通过后执行的 api 请求操作
    const submitCallback = () => {
        baTable.form.submitLoading = true
        // 创建表单数据的深拷贝，确保请求参数不被响应式系统或其他钩子函数修改
        const submitData = JSON.parse(JSON.stringify(baTable.form.items!))
        console.log('提交的参数:', submitData)
        baTable.api
            .postData(operate, submitData)
            .then((res) => {
                baTable.onTableHeaderAction('refresh', {})
                baTable.form.operateIds?.shift()
                if (baTable.form.operateIds!.length > 0) {
                    baTable.toggleForm('Edit', baTable.form.operateIds)
                } else {
                    baTable.toggleForm()
                }
                baTable.runAfter('onSubmit', { res })
            })
            .finally(() => {
                baTable.form.submitLoading = false
            })
    }

    if (formRef.value) {
        formRef.value.validate((valid: boolean) => {
            if (valid) {
                submitCallback()
            }
        })
    } else {
        submitCallback()
    }
}

// 获取商家数据的方法
const fetchMerchants = async () => {
    try {
        console.log('开始获取商家数据...')
        const response = await createAxios({
            url: '/business/business/index',
            method: 'get',
            params: {
                limit: 1000,
                field: 'id,name,weigh',
                orderBy: 'weigh desc,id asc'
            }
        })

        console.log('商家数据响应:', response)

        // 检查响应数据格式
        if (!response || !response.data || !Array.isArray(response.data.rows)) {
            console.error('商家数据格式不正确:', response)
            return
        }

        const merchants = response.data.rows
        const options: any[] = []

        // 构建商家选项
        merchants.forEach(merchant => {
            options.push({
                id: merchant.id,
                label: merchant.name,
                value: merchant.id,
                ...merchant // 保留所有商家数据，方便处理回调
            })
        })

        console.log('构建的商家选项:', options)
        merchantOptions.value = options
    } catch (error) {
        console.error('获取商家数据失败:', error)
    }
}


</script>

<style scoped lang="scss">
.image-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    border-radius: var(--el-border-radius-small);
    box-shadow: var(--el-box-shadow-light);
    border: 1px dashed var(--el-border-color);
    cursor: pointer;
    overflow: hidden;
    width: 110px;
    height: 110px;
}

.image-uploader:hover {
    border-color: var(--el-color-primary);
}

.image {
    width: 110px;
    height: 110px;
    display: block;
}

.image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.form-section {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--el-border-color);
}

.form-section:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 20px;
    color: var(--el-text-color-primary);
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-input__wrapper) {
    border-radius: var(--el-border-radius-base);
}

/* 规格管理界面样式 */
.form-sku {
    // margin-top: 20px;
    // padding: 15px;
    border-radius: 4px;
    width: 100%;
}

/* 规格名称输入区域 */
.spec-name-input {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

/* 规格属性项 */
.spec-attribute-item {
    margin-bottom: 20px;
    padding: 15px;
    background-color: white;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
}

/* 规格属性头部 */
.spec-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.spec-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
}

/* 规格值列表 */
.spec-values {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 10px;
    min-height: 40px;
}

/* 规格值标签 */
.spec-value-tag {
    display: flex;
    align-items: center;
    background-color: #ecf5ff;
    border: 1px solid #d9ecff;
    color: #409eff;
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 14px;
}

.spec-value-tag span {
    margin-right: 8px;
}

.spec-values .el-input {
    min-width: 150px;
}

/* 规格图片上传 */
.avatar-uploader .avatar {
    width: 40px;
    height: 40px;
    object-fit: cover;
}

/* 无SKU提示 */
.no-sku-hint {
    text-align: center;
    padding: 40px;
    color: #909399;
    background-color: white;
    border-radius: 4px;
    margin-top: 10px;
}

.params-container {
    width: 100%;
}

.params-header {
    display: flex;
    margin-bottom: 10px;
    font-weight: bold;
}

.param-col-name,
.param-col-value,
.param-col-action {
    padding: 0 10px;
}

.param-col-name {
    width: 200px;
}

.param-col-value {
    flex: 1;
}

.param-col-action {
    width: 80px;
}

.param-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    gap: 10px;
}

.param-input-name {
    width: 200px;
}

.param-input-value {
    flex: 1;
}

.param-actions {
    width: 80px;
    display: flex;
    justify-content: center;
}

.add-param-btn {
    margin-top: 10px;
}
</style>
